import sqlite3
import os
import os.path

# 这个程序仅用于安装环境

if __name__ == '__main__':
    path = os.path.abspath(__file__)
    dirname, useless = os.path.split(path)
    ROOT_DIR = dirname + '/'
    DB_CREATE_FILE_NAME = ROOT_DIR + 'sql/create.sql'
    DB_INSERT_FILE_NAME = ROOT_DIR + 'sql/add_basic_data.sql'
    DATA_DIR_NAME = ROOT_DIR + 'data/'
    DATA_TMP_DIR_NAME = DATA_DIR_NAME + 'tmp/'
    DB_FILE_NAME = DATA_DIR_NAME + '/ka.db'
    CONF_DIR = ROOT_DIR + 'conf/'
    LOG_DIR = ROOT_DIR + 'log/'

    # 检查相关文件是否齐全
    file_check_list = [DB_CREATE_FILE_NAME, DB_INSERT_FILE_NAME]
    for file_name in file_check_list:
        if os.path.exists(file_name) == False:
            print('Error: missing file: %s\n\nexit.'%(file_name))
            exit(1)

    # 检查文件夹是否已经存在
    dir_check_list = [DATA_DIR_NAME, CONF_DIR, LOG_DIR]
    for dir_name in dir_check_list:
        if os.path.exists(dir_name) == True:
            print('Error: \'%s\' is already exist!'%(dir_name))
            exit(1)

    # 创建数据文件夹
    print('creating files ...')
    os.mkdir(DATA_DIR_NAME)
    os.mkdir(DATA_TMP_DIR_NAME)
    os.mkdir(CONF_DIR)
    os.mkdir(LOG_DIR)

    # 读取创建数据库SQL文件内容
    print('preparing database ...')
    f = open(DB_CREATE_FILE_NAME, encoding='utf-8')
    create_sql_content = f.read()
    f.close()
    f = open(DB_INSERT_FILE_NAME, encoding='utf-8')
    add_basic_data_sql_content = f.read()
    f.close()

    # 创建数据库
    print('creating database ...')
    try:
        connect = sqlite3.connect(DB_FILE_NAME)
        connect.executescript(create_sql_content)
        print('adding basic data ...')
        connect.executescript(add_basic_data_sql_content)
        connect.commit()
        connect.close()
    except Exception as e:
        print('Error:', e)
        exit(1)

    print('finished!')
